package com.ybkj.daijia.server.service.impl;

import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.mapper.AdvertisementMapper;
import com.ybkj.daijia.server.model.Advertisement;
import com.ybkj.daijia.server.service.AdvertisementService;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DefaultAdvertisementService implements AdvertisementService {

    @Autowired
    private AdvertisementMapper advertisementMapper;

    @Override
    public Advertisement createAdvertisement(Long companyId,
        String companyName, String linkAddress, Integer sequence,
        String picture) {
        Advertisement advertisement = new Advertisement();
        advertisement.setSequence(sequence);
        advertisement.setCompanyId(companyId);
        advertisement.setCompanyName(companyName);
        advertisement.setLinkAddress(linkAddress);
        advertisement.setPicture(picture);
        advertisementMapper.insertRecord(advertisement);
        return advertisement;
    }

    @Override
    public Page<Advertisement> advertisementData(String companyName) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Integer offset = Pager.getPage() * Pager.getLimit();
        if (StringUtils.isBlank(companyName)) {
            companyName = null;
        } else {
            companyName = "%" + companyName + "%";
        }
        List<Advertisement> list = advertisementMapper
            .advertisementData(companyName, offset, Pager.getLimit());
        Long count = advertisementMapper.advertisementTotal(companyName);
        return new PageImpl<Advertisement>(list, pageable, count);
    }

    @Override
    public Advertisement findById(Long id) {

        return advertisementMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Advertisement advertisement) {

        advertisementMapper.deleteByPrimaryKey(advertisement.getId());
    }

    @Override
    public List<Advertisement> findByCompanyId(Long companyId) {

        return advertisementMapper.findByCompanyId(companyId);
    }

    @Override
    public Advertisement updateAdvertisement(Advertisement advertisement) {
        advertisement.setUpdated(new Date());
        advertisementMapper.updateById(advertisement);
        return advertisement;
    }


}
